<template>
  <div>
    <header class="head-container">
      <div class="flex-x-start-center">
        <div class="title">
          {{ oprType && oprType === OPR_TYPE.ADD ? "新增" : "编辑" }}方案
        </div>
        <el-button-group>
          <el-button size="small" round @click="goBack">返回
          </el-button>
          <el-button type="primary" size="small" round @click="handleSubmit">保存
          </el-button>
        </el-button-group>
      </div>
    </header>
    <el-divider />
    <el-form ref="formRef" :model="formData" label-width="200px" size="small" :rules="rules" style="width: 100%">
      <el-form-item label="选择商品：" prop="productId">
        <template v-if="formData.productId && oprType === OPR_TYPE.ADD">
          {{ temGoodInfo.title }}
        </template>

        <template v-if="formData.productName && oprType === OPR_TYPE.EDIT">
          {{ formData.productName }}
        </template>

        <el-button type="text" @click="dialogProductVisible = true">{{ formData.productId ? "更换" : "选择" }}商品</el-button>
      </el-form-item>

      <el-form-item label="服务时长：" prop="serviceDuration">
        <el-input
          v-model="formData.serviceDuration"
          placeholder="请输入服务时长"
          style="width:200px"
          size="medium"
          @input="(e)=>{$set(formData, 'serviceDuration', e.replace(/[^\d]/g, ''))}"
        >
          <template slot="append">分钟</template>
        </el-input>
      </el-form-item>

      <el-form-item label="同时段接待数：" prop="receptionQuantity">
        <el-input
          v-model="formData.receptionQuantity"
          placeholder="请输入同时段接待数"
          size="medium"
          style="width:200px"
          @input="(e)=>{$set(formData, 'receptionQuantity', e.replace(/[^\d]/g, ''))}"
        >
          <template slot="append">份</template>
        </el-input>
        <i
          style="margin:2px 0 0 6px;font-size: 30px;"
          class="el-icon-warning-outline"
          @click="popup = true,selectImg=1"
        />
      </el-form-item>

      <el-form-item label="关联资源：" prop="categoryList">
        <template v-if="formData.categoryList.length > 0">
          <el-tag
            v-for="tag in formData.categoryList"
            :key="tag.id"
            closable
            size="mini"
            style="margin-right: 10px"
            @close="handleDelResource(tag)"
          >
            {{ tag.name }}
          </el-tag>
        </template>
        <i style="margin-right:6px" class="el-icon-warning-outline" @click="popup = true,selectImg=2" />
        <el-button type="text" @click="dialogResourceVisible = true">添加关联资源</el-button>
      </el-form-item>

      <el-form-item label="状态：" prop="status">
        <el-switch
          v-model="formData.status"
          active-color="#ffb72f"
          inactive-color="red"
          :active-value="1"
          :inactive-value="0"
        />
      </el-form-item>
    </el-form>

    <el-dialog title="选择商品" :visible.sync="dialogProductVisible" width="90%">
      <div style="height: 50vh">
        <product-manage v-if="dialogProductVisible" mode-info.sync="modeInfo" @choose="handleChooseGood" />
      </div>
    </el-dialog>

    <el-dialog title="选择关联资源" :visible.sync="dialogResourceVisible" width="90%">
      <div style="height: 70vh">
        <resource-mange
          v-if="dialogResourceVisible"
          :category-list="formData.categoryList"
          @clickSingleChoice="onClickSingleChoice"
          @clickMultipleChoice="onClickMultipleChoice"
          @close="dialogResourceVisible=false"
        />
      </div>
    </el-dialog>
    <Pop :popup.sync="popup" :select-img="selectImg" />
  </div>
</template>

<script>
import { OPR_TYPE } from '@/views/wxaReservationModule/views/projectPlanManage/config'
import ProductManage from '@/views/wxaReservationModule/views/projectPlanManage/components/ProductManage'
import ResourceMange from '@/views/wxaReservationModule/views/projectPlanManage/components/ResourceMange'
import Pop from '@/views/wxaReservationModule/views/shopManage/components/modules/pop.vue'
import {
  addAppointmentPlanDetail,
  getAppointmentPlanDetail,
  updateAppointmentPlanDetail
} from '@/api/reservation'
export default {
  name: 'Index',
  components: { ProductManage, ResourceMange, Pop },
  props: {
    oprType: {
      type: String,
      default: OPR_TYPE.ADD
    }
  },
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入服务时长'))
      } else if (value < 30) {
        callback(new Error('整数。请输入30倍数的服务时长，如30、60、90、120,最高限1440'))
      } else if (value > 1440) {
        callback(new Error('整数。请输入30倍数的服务时长，如30、60、90、120,最高限1440'))
      } else if (value % 30 !== 0) {
        callback(new Error('整数。请输入30倍数的服务时长，如30、60、90、120,最高限1440'))
      } else {
        callback()
      }
    }
    const validateNumPass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入同时段接待数'))
      } else if (value == 0) {
        callback(new Error('整数。最小为1，最大为9999,9999则为无限'))
      } else if (value > 99999999) {
        callback(new Error('整数。最小为1，最大为9999,9999则为无限'))
      } else {
        callback()
      }
    }
    return {
      // ----商品档案 start----
      dialogProductVisible: false,
      temGoodInfo: null,
      modeInfo: {
        mode: 'manage',
        modePage: '',
        data: ''
      },
      // ----商品档案 end----
      // ----关联资源 start----
      dialogResourceVisible: false,
      // ----关联资源 end----
      OPR_TYPE,
      formData: {
        categoryList: [],
        productId: '',
        receptionQuantity: '',
        serviceDuration: '',
        status: 1
      },
      detailId: 0,
      rules: {
        productId: [{ required: true, message: '请选择商品', trigger: 'blur' }],
        serviceDuration: [
          { required: true, message: '整数。请输入30倍数的服务时长，如30、60、90、120,最高限1440', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ],
        receptionQuantity: [
          { required: true, message: '整数。最小为1，最大为9999,9999则为无限', trigger: 'blur' },
          { validator: validateNumPass, trigger: 'blur' }
        ]
      },
      popup: false,
      selectImg: 0

    }
  },
  methods: {
    async setQuery(row) {
      const { id } = row
      this.detailId = id
      const { code, data } = await getAppointmentPlanDetail({ id })
      if (code === 0) {
        this.formData = data
      }
    },
    goBack() {
      this.$emit('back')
    },
    handleSubmit() {
      this.$refs.formRef.validate(async(validate) => {
        console.log(validate)
        if (validate) {
          const params = {
            categoryList: this.formData.categoryList.map((v) => v.appointmentCategoryId),
            productId: this.formData.productId,
            receptionQuantity: this.formData.receptionQuantity,
            serviceDuration: this.formData.serviceDuration,
            status: this.formData.status
          }
          const api =
            this.oprType === OPR_TYPE.ADD
              ? addAppointmentPlanDetail
              : updateAppointmentPlanDetail
          if (this.oprType === OPR_TYPE.EDIT) {
            params.id = this.detailId
          }
          const { code } = await api(params)
          if (code === 0) {
            this.$message.success('保存成功')
            this.goBack()
          }
        }
      })
    },
    handleChooseGood(val) {
      this.formData.productId = val.goodsId
      this.temGoodInfo = val
      this.dialogProductVisible = false
    },
    onClickSingleChoice(val) {
      const { id } = val
      const len = this.formData.categoryList.filter(
        (v) => v && v.appointmentCategoryId === id
      ).length
      if (len === 0) {
        this.formData.categoryList.push(val)
      }
    },
    onClickMultipleChoice(rows) {
      this.formData.categoryList = []
      rows.forEach((v) => {
        this.onClickSingleChoice(v)
      })
      this.dialogResourceVisible = false
    },
    handleDelResource({ id }) {
      const index = this.formData.categoryList.map((v) => v.id).indexOf(id)
      this.formData.categoryList.splice(index, 1)
    }
  }
}
</script>

<style scoped lang="scss">
/*head*/
.head-container {
  height: 45px;

  .title {
    font-size: 20px;
    font-weight: bold;
    margin-right: 20px;
  }
}

.el-divider {
  margin: 10px 0 20px;
}

.text {
  font-size: 12px;
  color: $light-font-color;
}
</style>
